package com.blog.cloud.auth.controller;

import com.blog.cloud.api.utils.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 用户表(User)表控制层
 *
 * @author 龙茶清欢
 * @since 2024-08-15 19:51:58
 */
@RestController
@RequestMapping("/token")
@RequiredArgsConstructor
@Tag(name = "用户表管理", description = "用户表管理")
public class TokenController {
    
    @PostMapping("/login")
    public String login(String username, String password) {
        // TODO: 实现登录逻辑
        return "token";
    }

    /**
     * 三方授权登录，使用 JustAuth 实现
     * JustAuth 官方文档 https://www.justauth.cn/
     * @param type 第三方标识
     * @param response 响应信息
     * @throws IOException 异常
     */
    @GetMapping("/login/{type}")
    public void loginBySource(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = factory.get(type);
        String redirectUrl = authRequest.authorize(AuthStateUtils.createState());
        response.sendRedirect(redirectUrl);
    }

    /**
     * 授权回调，使用 JustAuth 实现
     * JustAuth 官方文档 https://www.justauth.cn/
     * @param type 第三方标识
     * @param callback 回调关键信息
     * @return 用户信息
     */
    @GetMapping("/{type}/callback")
    public R<Object> callBack(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        AuthResponse response = authRequest.login(callback);
        // TODO 从response中封装UserInfoVO用户信息，然后返回给前端
        if (response.getCode() != 2000) {
            return R.failed("授权获取用户信息失败");
        }
        AuthUser authUser = (AuthUser) response.getData();
        UserVO userVO = authService.callBack(authUser);

        Object data = (AuthUser)response.getData();
        return R.ok(data);
    }
    
    @PostMapping("/logout")
    public String logout() {
        // TODO: 实现登出逻辑
        return "logout";
    }

    @PostMapping("/refreshToken")
    public String refreshToken(String token) {
        // TODO: 实现刷新token逻辑
        return "refreshToken";
    }

    @PostMapping("/verifyToken")
    public boolean verifyToken(String token) {
        // TODO: 实现验证token逻辑
        return true;
    }


    @PostMapping("/getUserInfo")
    public Object getUserInfo(String token) {
        // TODO: 实现获取用户信息逻辑
        return null;
    }

    @PostMapping("/getPermissions")
    public Object getPermissions(String token) {
        // TODO: 实现获取用户权限逻辑
        return null;
    }


}
